<template>
  <div @back="() => $router.go(-1)">
    <div class="permissionContent">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-row :gutter="48">
          <a-col :md="12" :sm="24">
            <a-form-model-item :label="$t('all.autotext128')" prop="name">
              <a-input v-model="form.name" :maxLength="50" @blur="handleNameChange" />
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-model-item :label="$t('all.autotext273')" prop="description">
              <a-input v-model="form.description" :maxLength="100" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="48">
          <a-col :md="12" :sm="24">
            <a-form-model-item prop="repeat" :label="$t('all.autotext1165')">
              <div style="display:flex;align-items:center;height:40px">
                <a-radio-group v-model="form.copyVisible" @change="handleCopyChange" >
                  <a-radio :value="0">{{ $t('all.autotext957') }}</a-radio>
                  <a-radio :value="1">{{ $t('all.autotext279') }}</a-radio>
                </a-radio-group>
                <a-select
                  v-if="form.copyVisible == 1"
                  v-model="roleId"
                  style="width:200px"
                  @change="handleUserRoleChange"
                >
                  <a-select-option v-for="item in userRoleList" :key="item.roleId" :value="item.roleId">{{ item.roleName }}</a-select-option>
                </a-select>
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-model-item :label="$t('all.autotext1524')" prop="code">
              <a-radio-group name="radioGroup" v-model="form.code" @change="e => handleCodeChange(e.target.value)">
                <a-radio
                  v-for="item in roleCodeList"
                  :key="item"
                  :value="item"
                  style="height:30px"
                  :disabled="item == 'Subjects' || form.copyVisible === 1 || item == 'PROJECT_ADMIN'"
                >
                  {{ item }}
                </a-radio>
                <a-input
                  v-if="showCodeInput"
                  style="width:180px;height: 30px;"
                  v-model="codeInputValue"
                  :maxLength="20"
                />
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-tabs v-model="currentTab" >
          <a-tab-pane v-if="$store.getters.project != null && pcVisible" key="1" :tab="$t('all.autotext136')" >
            <a-row :gutter="48">
              <a-col :span="12">
                <a-form-model-item ref="ptsVisible" prop="ptsVisible" :label="$t('all.autotext11')">
                  <a-radio-group v-model="form.ptsVisible">
                    <a-radio :value="1">{{ $t('all.autotext943') }}</a-radio>
                    <a-radio :value="0">{{ $t('all.autotext927') }}</a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="12" v-if="form.code === $t('all.autotext579')">
                <a-form-model-item :label="$t('all.autotext45')">
                  <a-checkbox v-model="readonlyPermissionChecked" @change="handleReadonlyChange" :disabled="form.copyVisible === 1">{{ $t('all.autotext1011') }}</a-checkbox>
                </a-form-model-item>
              </a-col>
            </a-row>
            <PermissionTable
              ref="pcTable"
              :is-edit="true"
              :permission="form.code === 'CRA'?permissionCRA: permission"
              @check="checkedArr"
              :disableAll="selectedRole.roleCode === 'Subjects'"
            />
          </a-tab-pane>
          <a-tab-pane
            v-if="$store.getters.project != null && miniVisible"
            key="3"
            :tab="$t('all.autotext664')"
          >
            <PermissionTable
              ref="MPTable"
              :is-edit="true"
              :permission="permissionMP"
              @check="checkedArrMP"
              :disableAll="selectedRole.roleCode === 'Subjects'"
            />
          </a-tab-pane>
          <a-tab-pane v-if="$store.getters.project == null" key="4" :tab="$t('all.autotext1124')" >
            <a-row :gutter="48">
              <a-col :span="12">
                <a-form-model-item ref="ptsVisible" prop="ptsVisible" :label="$t('all.autotext11')">
                  <a-radio-group v-model="form.ptsVisible">
                    <a-radio :value="1">{{ $t('all.autotext943') }}</a-radio>
                    <a-radio :value="0">{{ $t('all.autotext927') }}</a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="12" v-if="form.code === $t('all.autotext579')">
                <a-form-model-item :label="$t('all.autotext45')">
                  <a-checkbox v-model="readonlyPermissionChecked" @change="handleReadonlyChange">{{ $t('all.autotext1011') }}</a-checkbox>
                </a-form-model-item>
              </a-col>
            </a-row>
            <PermissionTable
              ref="Table"
              :is-edit="true"
              :permission="permission"
              @check="checkedArr"
              :disableAll="selectedRole.roleCode === 'Subjects'"
            />
          </a-tab-pane>
          <a-button
            v-if="pcVisible || miniVisible || $store.getters.project == null"
            type="danger"
            ghost
            slot="tabBarExtraContent"
            @click="clearPermission"
          >
            {{ $t('all.autotext309') }}
          </a-button>
        </a-tabs>
        <!-- <div v-if="$store.getters.project != null">
          <a-form-model-item v-show="pcVisible" ref="account" label="项目权限-PC端">
            <a-tree
              v-model="checkedKeys"
              :replaceFields="replaceFields"
              checkable
              :tree-data="permission"
              @check="checkedArr"
              :checkStrictly="true"
            />
          </a-form-model-item>
          <a-form-model-item v-show="miniVisible" ref="account_mp" label="项目权限-小程序">
            <a-tree
              v-model="checkedKeysMP"
              :replaceFields="replaceFields"
              checkable
              :tree-data="permissionMP"
              @check="checkedArrMP"
              :checkStrictly="true"
            />
          </a-form-model-item>
        </div>
        <div v-else>
          <a-form-model-item ref="account" label="权限">
            <a-tree
              v-model="checkedKeys"
              :replaceFields="replaceFields"
              checkable
              :tree-data="permission"
              @check="checkedArr"
              :checkStrictly="true"
            />
          </a-form-model-item>
        </div> -->
      </a-form-model>
      <div class="drawer-btn" style="margin-top:20px">
        <center>
          <a-button :style="{ marginRight: '8px' }" @click="handleCancel">{{ $t('all.autotext975') }}</a-button>
          <a-button :loading="buttonLoading" type="primary" @click="onSubmit">{{ $t('all.autotext792') }}</a-button>
        </center>
      </div>
    </div>
  </div>
</template>
<script>



import { addRole, addRoleByPro, getProjectUserRole, getSystemUserRole, craDefaultRole } from '@/api/system/role.js'
import PermissionTable from './components/components/permissionTable.vue'
import { COMMON_ROLE_PERMISSION_SYS_CODE, COMMON_ROLE_PERMISSION_PRO_CODE } from '@/constants/common'

export default {
  components: {
    PermissionTable
  },
  data () {
    return {
      currentTab: this.$store.getters.project != null ? '1' : '4',
      // 确认按钮loading状态
      buttonLoading: false,
      maskClosable: true,
      checkedKeys: [], // 树状keys
      checkedKeysMP: [],
      autoExpandParent: true,
      readonlyPermissionChecked: false,
      form: {
        name: '',
        code: '',
        description: '',
        menuIds: '',
        menuIdsMP: '',
        copyVisible: 0,
        ptsVisible: ''
      },
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id'
      },
      labelCol: {
        span: 4
      },
      wrapperCol: {
        span: 19
      },
      other: '',
      rules: {
        name: [
          {
            required: true,
            message: this.$t('all.autotext1219'),
            trigger: 'blur'
          },
          {
            min: 1,
            max: 50,
            message: this.$t('all.autotext737'),
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: this.$t('all.autotext1245'),
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: this.$t('all.autotext210'),
            trigger: 'blur'
          }
        ],
        description: [
          {
            required: false,
            trigger: 'blur'
          },
          {
            min: 1,
            max: 100,
            message: this.$t('all.autotext355'),
            trigger: 'blur'
          }
        ]
      },
      roleCodeList: [],
      codeInputValue: '',
      showCodeInput: false,
      pcVisible: false,
      miniVisible: false,
      roleId: '',
      userRoleList: [],
      permission: [],
      permissionCRA: [],
      permissionPad: [],
      permissionMP: [],
      rolePermisionCra: [],
      selectedRole: {}
    }
  },
  computed: {
    isOtherCode () {
      return this.form.code === this.$t('all.autotext579')
    }
  },
  mounted () {
    // this.craDefaultRole()
    const roles = localStorage.getItem('CURRENT_PERMISSION')

    if (roles) {
      const mData = JSON.parse(roles)
      this.permission = mData.permission
      this.permissionCRA = mData.permission
      this.permissionPad = mData.permissionPad
      this.permissionMP = mData.permissionMP
    }

    this.currentTab = this.$store.getters.project != null ? '1' : '4'
    this.roleCodeList = this.$store.getters.project === null ? COMMON_ROLE_PERMISSION_SYS_CODE : COMMON_ROLE_PERMISSION_PRO_CODE
    this.$nextTick(() => {
      if (this.$refs.pcTable !== undefined) {
        this.$refs.pcTable.updataView()
      }
      if (this.$refs.Table !== undefined) {
        this.$refs.Table.updataView()
      }
      if (this.$refs.MPTable !== undefined) {
        this.$refs.MPTable.updataView()
      }
    }, 500)
  },
  methods: {
    getAllPermissions () {
      const roles = localStorage.getItem('CURRENT_PERMISSION')
      if (roles) {
        const mData = JSON.parse(roles)
        this.permission = mData.permission
        this.permissionCRA = mData.permission
        this.permissionPad = mData.permissionPad
        this.permissionMP = mData.permissionMP
      }
    },
    getDefaultCheckedAndDisabledId (permissionList) {
      if (!this.form.code) {
        return ({
          checkedIdList: [],
          disabledIdList: []
        })
      }
      const { checkedIdList, disabledIdList } = this.getDataByRecursion(permissionList)
      return {
        checkedIdList,
        disabledIdList
      }
    },
    getDataByRecursion (data = [], checkedIdList = [], disabledIdList = []) {
      const code = this.readonlyPermissionChecked ? this.$t('all.autotext1011') : this.form.code
      const handleItem = (item) => {
        const { greyRoles, selectedRoles, id, child } = item
        if (greyRoles?.includes(code)) {
          disabledIdList.push(id)
        }
        if (selectedRoles?.includes(code)) {
          checkedIdList.push(id)
        }
        if (child && child.length) {
          child.forEach(e => handleItem(e))
        }
      }
      data.forEach(item => {
        const { children } = item
        handleItem(item)
        // todo 尾递归优化
        if (children && children.length) {
          this.getDataByRecursion(children, checkedIdList, disabledIdList)
        }
      })
      return {
        checkedIdList,
        disabledIdList
      }
    },
    updateView () {
      this.$nextTick(() => {
        if (this.$refs.pcTable !== undefined) {
          this.$refs.pcTable.updataView()
        }
        if (this.$refs.Table !== undefined) {
          this.$refs.Table.updataView()
        }
        if (this.$refs.MPTable !== undefined) {
          this.$refs.MPTable.updataView()
        }
      }, 500)
    },
    /**
     * 设置当前角色默认权限
     * @param systemId 1-PC 4-小程序(只有受试者)
     * @param roleCode
     */
    setDefaultPermission (systemId, roleCode) {
      const permissionList = systemId === 4 ? this.permissionMP : roleCode === 'CRA' ? this.permissionCRA : this.permission
      const { checkedIdList, disabledIdList } = this.getDefaultCheckedAndDisabledId(permissionList)
      if (systemId === 4) {
        this.form.menuIdsMP = checkedIdList
        this.setCheckedParams(this.permissionMP, checkedIdList, disabledIdList)
        return
      }
      if (roleCode === 'CRA') {
        this.form.menuIds = checkedIdList
        this.setCheckedParams(this.permissionCRA, checkedIdList, disabledIdList)
        return
      }
      this.form.menuIds = checkedIdList
      if (roleCode !== 'Subjects') {
        this.setCheckedParams(this.permission, checkedIdList, disabledIdList)
      }
    },
    async craDefaultRole () {
      const res = await craDefaultRole({
        proId: this.$store.getters.project.id,
        systemId: this.$const.SYSTEM_TYPE.PAYMENT.value
      })
      this.rolePermisionCra = res
    },
    handleCopyChange (e) {
      if (e.target.value === 1) {
        this.getUserRoleList()
      }
    },
    handleNameChange () {
      this.getUserRoleList()
    },
    getUserRoleList () {
      if (this.$store.getters.project == null) {
        getSystemUserRole({ name: this.form.name }).then(res => {
          this.userRoleList = res
        })
      } else {
        getProjectUserRole({ name: this.form.name, proId: this.$store.getters.project.id }).then(res => {
          this.userRoleList = res
        })
      }
    },
    onSubmit () {
      this.buttonLoading = true
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.showCodeInput && !this.codeInputValue) {
            this.buttonLoading = false
            this.$message.warning(this.$t('all.autotext301'))
            return
          }
          const menuIds = []
          if (this.pcVisible && this.form.menuIds && this.form.menuIds.length) {
            menuIds.push(...this.form.menuIds)
          }
          if (this.miniVisible && this.form.menuIdsMP && this.form.menuIdsMP.length) {
            menuIds.push(...this.form.menuIdsMP)
          }
          if (this.$store.getters.project != null) {
            addRoleByPro({
              ...this.form,
              code: this.showCodeInput ? this.codeInputValue : this.form.code,
              menuIds: menuIds.join(','),
              proId: this.$store.getters.project.id,
              systemId: this.$const.SYSTEM_TYPE.PAYMENT.value,
              readonly: this.isOtherCode ? +this.readonlyPermissionChecked : 0
            })
              .then(res => {
                this.buttonLoading = false
                this.$message.success(this.$t('all.autotext1243'))
                this.createRole()
                this.handleOk()
              })
              .catch(() => {
                this.buttonLoading = false
              })
          } else {
            addRole({
              ...this.form,
              menuIds: menuIds.join(','),
              code: this.showCodeInput ? this.codeInputValue : this.form.code,
              systemId: this.$const.SYSTEM_TYPE.PAYMENT.value,
              readonly: this.isOtherCode ? +this.readonlyPermissionChecked : 0
            })
              .then(res => {
                this.buttonLoading = false
                this.$message.success(this.$t('all.autotext1243'))
                this.createRole()
                this.handleOk()
              })
              .catch(() => {
                this.buttonLoading = false
              })
          }
        } else {
          this.buttonLoading = false
          return false
        }
      })
    },
    checkedArr (checkedKeys) {
      this.form.menuIds = checkedKeys
    },
    checkedArrMP (checkedKeys) {
      this.form.menuIdsMP = checkedKeys
    },
    resetForm () {
      this.roleId = ''
      this.form.copyVisible = 0
      this.showCodeInput = false
      this.codeInputValue = ''
      this.$refs.ruleForm.resetFields()
      this.checkedKeys = []
      this.checkedKeysMP = []
      this.miniVisible = true
      this.btnVisible = true
      this.$forceUpdate()
    },
    // 选择集合
    collectRow (Rows) {
      this.selectedGroud = Rows
    },
    // 处理取消
    handleCancel () {
      this.buttonLoading = false
      this.$router.go(-1)
    },
    // 处理确定按钮
    handleOk () {
      this.$router.go(-1)
    },
    createRole () {

    },
    // 处理用户权限
    handleUserRoleChange () {
      if (this.userRoleList && this.userRoleList.length) {
        const data = this.userRoleList.find(item => {
          return item.roleId === this.roleId
        })
        this.selectedRole = data
        if (data) {
          if (data.pms) {
            const rolePermission = data.pms.split(',').map(Number)
            this.form.menuIds = rolePermission
            this.setCheckedParams(this.permission, rolePermission)
            this.$nextTick(() => {
              if (this.$refs.pcTable !== undefined) {
                this.$refs.pcTable.updataView()
              }
              if (this.$refs.Table !== undefined) {
                this.$refs.Table.updataView()
              }
            }, 500)
          }
          if (data.mini) {
            const rolePermission = data.mini.split(',').map(Number)
            this.form.menuIdsMP = rolePermission
            this.setCheckedParams(this.permissionMP, rolePermission)
            this.$nextTick(() => {
              if (this.$refs.MPTable !== undefined) {
                this.$refs.MPTable.updataView()
              }
            }, 500)
          }
          this.form.ptsVisible = data.ptsVisible ? 1 : 0
          // todo: reactor 上下如何保持数据一致？？？
          if (
            (this.$store.getters.project == null && ['SYS_ADMIN', 'SYS_BIZ', 'SYS_FINANCE'].indexOf(data.roleCode) >= 0) ||
            (this.$store.getters.project != null && ['PROJECT_ADMIN', 'CRC', 'CRA', 'PM', 'Investigator', 'Subjects'].indexOf(data.roleCode) >= 0)
          ) {
            this.form.code = data.roleCode
            this.showCodeInput = false
            this.handleCodeChange(data.roleCode)
          } else {
            this.form.code = this.$t('all.autotext579')
            this.showCodeInput = true
            this.codeInputValue = data.roleCode
            this.handleCodeChange(data.roleCode)
          }
        }
      }
    },
    // todo: 💩 变量直接写死这么传？
    handleReadonlyChange (e) {
      const { checked } = e.target
      if (checked) {
        this.handleCodeChange(this.$t('all.autotext1011'))
      } else {
        this.handleCodeChange(this.$t('all.autotext579'))
      }
    },
    async handleCodeChange (value) {
      if (this.form.copyVisible) return
      if (value === this.$t('all.autotext579') && this.readonlyPermissionChecked) {
        value = this.$t('all.autotext1011')
      }
      if (!this.form.copyVisible) {
        this.setCheckedParams(this.permission, [])
      }

      const isSysRole = this.$store.getters.project === null

      if ([this.$t('all.autotext579'), this.$t('all.autotext1011')].includes(value)) {
        this.showCodeInput = true
        this.currentTab = '1'
      } else {
        this.showCodeInput = false
      }
      this.pcVisible = true

      this.currentTab = '1'
      if (['Subjects', 'Investigator'].includes(value) || isSysRole) {
        this.miniVisible = true
      } else {
        this.miniVisible = false
      }

      const isSubject = value === 'Subjects'
      if (isSubject) {
        this.pcVisible = false
        this.currentTab = '3'
      }

      await this.setDefaultPermission(isSubject ? 4 : 1, value)

      this.$nextTick(() => {
        if (this.$refs.pcTable !== undefined) {
          this.$refs.pcTable.updataView()
        }
        if (this.$refs.Table !== undefined) {
          this.$refs.Table.updataView()
        }
      }, 500)

      // 💩山堆💩
      // if (value === 'PM' || value === 'CRC') {
      //   this.miniVisible = false
      //   this.currentTab = '1'
      //   this.getDefaultPermission(1, value)
      // } else if (value === 'CRA') {
      //   this.form.menuIds = this.rolePermisionCra
      //   this.setCheckedParams(this.permissionCRA, this.rolePermisionCra)
      //   this.$nextTick(() => {
      //     if (this.$refs.pcTable !== undefined) {
      //       this.$refs.pcTable.updataView()
      //     }
      //     if (this.$refs.Table !== undefined) {
      //       this.$refs.Table.updataView()
      //     }
      //   }, 500)
      //
      //   this.miniVisible = false
      //   this.currentTab = '1'
      //   this.getDefaultPermission(1, value)
      // } else if (value === 'Investigator') {
      //   // this.pcVisible = false
      //   this.currentTab = '1'
      //   this.getDefaultPermission(1, value)
      // } else if (value === 'Subjects') {
      //   this.pcVisible = false
      //   this.currentTab = '3'
      //   this.getDefaultPermission(4, value)
      // } else {
      //   this.miniVisible = false
      //   this.currentTab = '1'
      //   this.getDefaultPermission(1, value)
      // }
      if (isSysRole) {
        // 如果是系统
        this.currentTab = '4'
      }
    },
    // 清空权限
    clearPermission () {
      if (this.currentTab === '1') {
        this.setPmsParams(this.permission)
        this.$refs.pcTable.clearAll()
      }
      if (this.currentTab === '3') {
        this.setPmsParams(this.permissionMP)
        this.$refs.MPTable.clearAll()
      }
      if (this.currentTab === '4') {
        this.setPmsParams(this.permissionMP)
        this.$refs.Table.clearAll()
      }
      this.$forceUpdate()
    },
    // 遍历加参数字段
    setPmsParams (permission) {
      if (permission && permission.length) {
        permission.forEach(item => {
          !item.disabled && (item.checked = false)
          if (item.child && item.child.length) {
            item.child.forEach(item1 => {
              !item1.disabled && (item1.checked = false)
            })
          }
          if (item.children) {
            this.setPmsParams(item.children)
          }
        })
      }
    },
    // 遍历加参数字段
    setCheckedParams (permission, rolePermission, disablePermissionList) {
      if (permission && permission.length) {
        // todo: 💩 下次看到必须重写
        permission.forEach(item => {
          if (rolePermission && rolePermission.indexOf(item.id) >= 0) {
            item.checked = true
          } else {
            item.checked = false
          }

          if (disablePermissionList && disablePermissionList.indexOf(item.id) >= 0) {
            item.disabled = true
          } else {
            item.disabled = false
          }

          if (item.child && item.child.length) {
            item.child.forEach(item1 => {
              if (rolePermission && rolePermission.indexOf(item1.id) >= 0) {
                item1.checked = true
              } else {
                item1.checked = false
              }
              if (disablePermissionList && disablePermissionList.indexOf(item1.id) >= 0) {
                item1.disabled = true
              } else {
                item1.disabled = false
              }
            })
          }
          if (item.children) {
            this.setCheckedParams(item.children, rolePermission, disablePermissionList)
          }
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
  .permissionContent{
    background:white;
    margin: 0 auto;
    padding: 20px;
  }

</style>
